import time

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from testData.all_sites_user_info import base_url
# from testcases.delete_campaign import campaign_id

from pages.base_page import Page


class AgentConsoleWindow(Page):
    ele_get_online_and_chat = (By.XPATH, u'//span[text()="Get Online & Chat"]')
    ele_visitors_tab = (By.XPATH, u'//span[text()="Visitors"]')
    ele_simulate = (By.XPATH, u'//a[text()="Simulate"]')
    ele_chat_button = (By.XPATH, u'//a[@class="chatButton--ripple chatButton"]')
    ele_iframe_chat_button = (By.XPATH, u'//iframe[@title="Chat button"]')
    ele_start_chatting = (By.XPATH, u'//button[@aria-label="Start Chatting"]')
    ele_message_text_area = (By.ID, u'chat-input-control')
    ele_click_to_send = (By.XPATH, u'//button[@aria-label="Click to send"]')
    ele_end_chat = (By.XPATH, u'//button[@aria-label="End Chat"]')
    ele_yes_to_leave_chatting = (By.ID, u'embedded-end-chatConfirmLeave')
    ele_chat_window_container = (By.ID, u'chat_window_container')
    ele_force_login = (By.XPATH, u'//span[text()="OK"]')

    # used for creating a new campaign
    ele_leve1_campaign_menu = (By.XPATH, u'//span[text()="Campaign"]')
    ele_select_campaign = (By.ID, u'level2menu-scopingSelector-campaign')
    ele_manage_button = (By.ID, u'level2menu-scopingSelector-campaign-manage')
    ele_new_campaign_button = (By.ID, u'table-campaign-button-new')

    # offline button
    ele_offline_chat_button = (By.XPATH, u'//a[@class="chatButton"]')

    # offline visitor window
    ele_email = (By.XPATH, u'//input[@type="email"]')
    ele_name = (By.XPATH, u'//input[@type="text"]')
    ele_offline_massage = (By.XPATH, u'//textarea')
    ele_submit = (By.XPATH, u'//button[@type="submit"]')

    ele_new_campaign_name = (By.ID, u'form-campaign-input-name')
    ele_new_campaign_save_button = (By.XPATH, u'//span[text()="Save"]')

    # 需要获取该元素的text属性
    ele_new_campaign_id = (By.XPATH, u'//a[text()="testAutomationTest"]/../../../td[@data-columnfield="id"]//span')

    # 关闭drawer
    ele_drawer_close = (By.XPATH, u'//button[@data-tag="drawerClose"]')

    def __init__(self, driver, url, site_id):
        # Page.__init__(self, driver, url)
        self.site_id = site_id
        self.url = url
        self.driver = driver

    def create_new_campaign(self):
        global new_campaign_id
        self.click(self.ele_leve1_campaign_menu)
        self.click(self.ele_select_campaign)
        self.click(self.ele_manage_button)
        self.click(self.ele_new_campaign_button)
        self.input_text(self.ele_new_campaign_name, "testAutomationTest")
        # self.driver.switch_to_default_content()
        self.click(self.ele_new_campaign_save_button)

        WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_xpath(u'//button[@data-tag="drawerClose"]'))
        try:
            new_campaign_id = self.find_element(*self.ele_new_campaign_id).text
        except Exception as e:
            print("新建的campaign在第二页或第二页以后，没有取到new_campaign_id")

        self.click(self.ele_drawer_close)
        return new_campaign_id if new_campaign_id is not None else "new_campaign_id没取到"

    def goto_agent_console(self):
        ele = self.find_element(*self.ele_get_online_and_chat)
        ActionChains(self.driver).key_down(Keys.LEFT_CONTROL).click(ele).key_up(Keys.LEFT_CONTROL).perform()
        # self.click(self.ele_get_online_and_chat)
        handle_list = self.driver.window_handles
        print("all handles===>", handle_list)

        # switch to agent console window
        self.driver.switch_to.window(handle_list[1])

        # 有时候会弹出force login弹窗，由于不是每一次都会弹出山，需要处理
        try:
            self.click(self.ele_force_login)
        except NoSuchElementException as e:
            print("没有弹出force login弹框", e)

        self.driver.switch_to.default_content()
        wait = WebDriverWait(self.driver, 30, 1)
        try:
            ele_visitor = wait.until(EC.presence_of_all_elements_located((By.XPATH, u'//a[text()="Simulate"]')))
        except Exception as e:
            print("agent已和visitor聊天", e)
        # self.driver.implicitly_wait(35)

    def goto_visitor_page_create_chat(self):

        # 直接拼接URL，新建tab到达visitor的URL
        visitor_url = base_url + r'/frontEnd/assets/livechat/previewpage/?campaignId=' + new_campaign_id + r'&siteId=' + self.site_id
        js = 'window.open("%s");' % visitor_url
        self.driver.execute_script(js)

        # self.click(self.ele_simulate)

        handle_list = self.driver.window_handles
        print(handle_list)

        # switch to visitor window
        self.driver.switch_to.window(handle_list[2])

        # 有些campaign我发现没有chat button，这样的话不能点击，需要捕捉异常
        try:
            iframe = self.find_element(*self.ele_iframe_chat_button)
            self.driver.switch_to.frame(iframe)
            self.click(self.ele_chat_button)

            # 返回当前主体窗口，进入另一个iframe
            self.driver.switch_to_default_content()
            iframe_chat_window_container = self.find_element(*self.ele_chat_window_container)
            self.driver.switch_to.frame(iframe_chat_window_container)
            time.sleep(5)

        except NoSuchElementException as e:
            print("没有找到这个iframe或chat button，可能这个campaign没有chat button", e)

        # 有些聊天窗口没有start chatting button，要作特殊处理
        try:
            self.click(self.ele_start_chatting)
        except NoSuchElementException as e:
            print("没有start chatting button", e)

        try:
            # 进入聊天窗口，输入文本，点击发送，关闭聊天窗口
            self.input_text(self.ele_message_text_area, "testAutomation")
            self.click(self.ele_click_to_send)
            self.click(self.ele_end_chat)
        except Exception as e:
            print("输入聊天信息或发送消息失败", e)

        # 最后的确认离开框可能不存在，catch异常
        try:
            self.click(self.ele_yes_to_leave_chatting)
        except NoSuchElementException as e:
            print("exception===>", e)

        self.driver.switch_to.default_content()

    def goto_visitor_page_create_offline_msg(self):
        # 直接拼接URL，新建tab到达visitor的URL
        visitor_url = base_url + r'/frontEnd/assets/livechat/previewpage/?campaignId=' + new_campaign_id + r'&siteId=' + self.site_id
        js = 'window.open("%s");' % visitor_url
        self.driver.execute_script(js)

        # self.click(self.ele_simulate)

        handle_list = self.driver.window_handles
        print(handle_list)

        # switch to visitor window
        self.driver.switch_to.window(handle_list[1])

        try:
            # 这个ele_iframe_chat_button有点问题，同一个button有的title是chat button
            # 有的是chat icon for button
            iframe = self.find_element(*self.ele_iframe_chat_button)
            self.driver.switch_to.frame(iframe)
            self.click(self.ele_offline_chat_button)

            # 返回当前主体窗口，进入另一个iframe
            self.driver.switch_to_default_content()
            iframe_chat_window_container = self.find_element(*self.ele_chat_window_container)
            self.driver.switch_to.frame(iframe_chat_window_container)
            time.sleep(5)

        except NoSuchElementException as e:
            print("没有找到这个iframe或chat button，可能这个campaign没有chat button", e)

        try:
            self.input_text(self.ele_name, "automationTest")
            self.input_text(self.ele_email, "comm100@100.com")
            self.input_text(self.ele_offline_massage, "offline message test")
            self.click(self.ele_submit)
        except NoSuchElementException as e:
            print("没有提交按钮或输入框，offline message创建失败", e)
